﻿using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Sharp.DataTransferObject;
using Sharp.Infrastructure;
using Sharp.Portal.Mvc.OAuth.Sharp.Server;
using Sharp.Portal.Owin;
using Sharp.ServiceContracts;

namespace Sharp.Services.OAuth.Controllers
{
    public class LoginController : Controller
    {


        // GET: OAuth/Login
        [AllowAnonymous]
        public ActionResult Index()
        {
            if (Request.IsAuthenticated)
            {
                return Redirect("~/Admin/Home");
            }
            return View();
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Index(UserDTO userParam)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }
            var isRemenber = Request.Form["isRemenber"].Contains("true");
            var roleName = Request.Form["ddl_Role"];
            Result<UserDTO> result;
            using (var proxy = new ServiceProxy<IUserService>())
            {
                result = proxy.Channel.TryLogin(userParam);
            }

            if (result.Success)
            {
                var user = result.Data;
                var cookiesIdentity = ClaimsIdentityCreate.GenerateUserIdentity(new SharpUser(user), DefaultAuthenticationTypes.ApplicationCookie);
                var role = user.Roles.Select(s => s.Name).FirstOrDefault(t => t == roleName);
                if (string.IsNullOrEmpty(role))
                {
                    ModelState.AddModelError("", "角色选择不正确.");
                    return View();
                }
                cookiesIdentity.AddRole(role);
                Request.GetOwinContext().Request.Context.Authentication.SignIn(new
                    AuthenticationProperties
                {
                    IsPersistent = isRemenber
                }, cookiesIdentity);
                var queryStr = Request.QueryString["Query"];
                if (!string.IsNullOrEmpty(queryStr))
                {
                    var queryControl = HttpUtility.ParseQueryString(queryStr);
                    if (queryControl.AllKeys.Any(x=>x=="ReturnUrl"))
                    {
                        return Redirect(queryControl["ReturnUrl"]);
                    }
                }
                return Redirect("~/Admin/Home");
            }
            ModelState.AddModelError("", result.Message);
            return View();
        }

        [Route("Logout")]
        public ActionResult Logout()
        {
            IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
            authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            return Redirect(Url.Content("Index"));
        }

        //[AllowAnonymous]
        //public ActionResult UserRoles(string userName, string likeUser)
        //{
        //    var user = _userService.GetUserByName(userName);
        //    if (user != null)
        //    {
        //        var results = user.Roles.Select(s => new { id = s.Name, text = s.Name })
        //            .Where(t => t.text.Contains(likeUser) || string.IsNullOrWhiteSpace(likeUser))
        //            .ToList();
        //        return Json(results, JsonRequestBehavior.AllowGet);
        //    }
        //    return Json(null, JsonRequestBehavior.AllowGet);
        //}

    }
}